import React, { useState } from 'react'
import styles from './index.module.scss'
import { Link } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { Card, Form, Input, Button, message } from 'antd'
import { validatePassword, validateUsername } from '../utils'

export interface FormValues {
  username: string
  password: string
}
const Login: React.FC = () => {
  const dispatch = useDispatch()
  const [messageApi, contextHolder] = message.useMessage()
  const [username, setUsername] = useState('admin')
  const [password, setPassword] = useState('@Fjf123456')

  // 保存用户名
  const handleUsername = (e: React.ChangeEvent<HTMLInputElement>) => {
    setUsername(e.target.value)
  }
  // 保存密码
  const handlePassword = (e: React.ChangeEvent<HTMLInputElement>) => {
    setPassword(e.target.value)
  }
  const onFinish = (values: FormValues) => {
    messageApi.open({
      type: 'success',
      content: '登录成功！'
    })
    dispatch({
      type: 'saveUser',
      payload: values
    })
  }

  return (
    <div className={styles.container}>
      {contextHolder}
      <Card>
        <p className={styles.title}>登录</p>
        <Form
          initialValues={{ remember: true }}
          onFinish={onFinish}>
          <Form.Item
            name='username'
            rules={[{ validator: validateUsername }]}>
            <Input
              value={username}
              placeholder='请输入用户名'
              onChange={handleUsername}
            />
          </Form.Item>
          <Form.Item
            name='password'
            rules={[{ validator: validatePassword }]}>
            <Input.Password
              value={password}
              placeholder='请输入密码'
              onChange={handlePassword}
            />
          </Form.Item>
          <Form.Item>
            <Button
              type='primary'
              htmlType='submit'>
              登录
            </Button>
          </Form.Item>
          <Form.Item>
            <Link to='/forget'>忘记密码</Link>
            <span className={styles.right}>
              没有账号？<Link to='/register'>快速注册</Link>
            </span>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
